package com.controller;

import com.model.TicketModel;
import com.services.ITicketServices;
import com.services.impl.TicketServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/flights/*/tickets")
public class FlightTicketsServletController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从URL中提取航班ID
            String pathInfo = request.getPathInfo();
            String flightId = pathInfo.split("/")[1];

            ITicketServices ticketServices = new TicketServicesImpl();
            List<TicketModel> tickets = ticketServices.getTicketsByFlightId(Integer.parseInt(flightId));
            
            result.put("code", 0);
            result.put("msg", "success");
            result.put("data", tickets);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "获取机票信息失败：" + e.getMessage());
        }
        
        response.getWriter().write(JSONObject.fromObject(result).toString());
    }
} 